package com.hippy.erya.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hippy.erya.base.auth.context.LoginContextHolder;
import com.hippy.erya.common.DateUtil;
import com.hippy.erya.entity.MemberDO;
import com.hippy.erya.entity.OrderDetailDO;
import com.hippy.erya.mapper.MemberMapper;
import com.hippy.erya.mapper.OrderDetailMapper;
import com.hippy.erya.query.BaseQueryWrapper;
import com.hippy.erya.sys.core.constant.cache.Cache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetailDO> {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private MemberMapper memberMapper;


    public Page<OrderDetailDO> queryByPage(Long currentPage, int limit,
                                           String orderChannel,
                                           String purchaseTimeRange) {
        Page<OrderDetailDO> page = new Page<>(currentPage, limit);
        QueryWrapper<OrderDetailDO> queryWrapper = BaseQueryWrapper.buildQuery();
        if (StringUtils.isNotEmpty(orderChannel)) {
            queryWrapper.eq("ORDER_PLATFORM", orderChannel);
        }
        BaseQueryWrapper.buildQuery(queryWrapper, purchaseTimeRange, "ORDER_CREATE_DATE");
        Page<OrderDetailDO> pageResult = orderDetailMapper.selectPage(page, queryWrapper);
        pageResult.getRecords().forEach(BaseQueryWrapper::outputMessage);
        return pageResult;
    }

    public void addOrderDetail(OrderDetailDO orderDetailDO) {
        String userCode = orderDetailDO.getUserCode();
        QueryWrapper<MemberDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_CODE", userCode);
        queryWrapper.eq("MEMBER_NAME", orderDetailDO.getMemberName());
        MemberDO memberDO = memberMapper.selectOne(queryWrapper);
        if (memberDO == null) {
            memberDO = new MemberDO();
            memberDO.setMemberCode(userCode);
            memberDO.setMemberName(orderDetailDO.getMemberName());
            memberDO.setMemberGrade("01");
            memberDO.setMembershipDate(new Date());
            memberDO.setUserCode(orderDetailDO.getUserCode());
            memberDO.setCreatedBy(orderDetailDO.getCreatedBy());
            memberDO.setOrderCount(1);
            memberDO.setOrderTotalAmount(orderDetailDO.getOrderPrice());
            memberMapper.insert(memberDO);
        } else {
            memberDO.setOrderCount(memberDO.getOrderCount()+ 1);
            memberDO.setOrderTotalAmount(memberDO.getOrderTotalAmount()+ orderDetailDO.getOrderPrice());
            updateMemberGrade(memberDO);
            memberMapper.updateById(memberDO);
        }
        orderDetailMapper.insert(orderDetailDO);
    }

    private void updateMemberGrade(MemberDO memberDO) {
        int orderCount = memberDO.getOrderCount();
        if (orderCount > 40) {
            memberDO.setMemberGrade("04");
        }else if (orderCount > 30) {
            memberDO.setMemberGrade("03");
        }else if (orderCount > 20) {
            memberDO.setMemberGrade("02");
        }
    }



    @Transactional(rollbackFor = Exception.class, timeout = 300)
    public void deleteOrderDetail(String orderIds) {
        String[] orderIdArray = StringUtils.split(orderIds, ",");
        String account = LoginContextHolder.getContext().getUser().getAccount();
        for (String orderId : orderIdArray) {
            if (StringUtils.isEmpty(orderId)) {
                continue;
            }
            int id = Integer.parseInt(orderId);
            OrderDetailDO orderDetailDO = orderDetailMapper.selectById(id);
            orderDetailDO.deleteData(account);
            orderDetailMapper.updateById(orderDetailDO);
        }

    }

    public List<OrderDetailDO> queryLatestOrderDetails() {
        QueryWrapper<OrderDetailDO> queryWrapper = BaseQueryWrapper.buildQuery();
        queryWrapper.ge("ORDER_CREATE_DATE", DateUtil.plusDays(DateUtil.getCurrentDate(), -7));
        return orderDetailMapper.selectList(queryWrapper);
    }


    public List<OrderDetailDO> queryOrderDetails(Date orderCreateDate, String userCode) {
        QueryWrapper<OrderDetailDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USABLE_FLAG", Cache.USABLE);
        queryWrapper.eq("USER_CODE", userCode);
        Date formatDate = DateUtil.formatToDate(orderCreateDate, DateUtil.DATE_SHOW_FORMAT);
        queryWrapper.ge("ORDER_CREATE_DATE", formatDate);
        queryWrapper.le("ORDER_CREATE_DATE", DateUtil.plusDays(formatDate, 1));
        return orderDetailMapper.selectList(queryWrapper);
    }

}
